﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NetDon.OA.Interface;
using NetDon.OA.Interface.CRM;
using NetDon.OA.Interface.Common;
using NetDon.OA.Interface.Configuration;
using NetDon.Utilities;

namespace NetDon.OA.Portal.Clerk
{
    public partial class ReceiptInfoTrackEdit : NavigationPageBase
    {
        protected Guid Id
        {
            set { ViewState["Id"] = value; }
            get
            {
                if (ViewState["Id"] != null)
                    return ViewState["Id"].ToString().ToGuid();
                return Guid.Empty;
            }
        }

        private IList<IssuingOrderReceiptInfoTrackCommentData> IssuingOrderReceiptInfoTrackComments
        {
            set { ViewState["IssuingOrderReceiptInfoTrackCommentData"] = value; }
            get
            {
                if (ViewState["IssuingOrderReceiptInfoTrackCommentData"] != null)
                    return ViewState["IssuingOrderReceiptInfoTrackCommentData"] as IList<IssuingOrderReceiptInfoTrackCommentData>;
                return new List<IssuingOrderReceiptInfoTrackCommentData>();
            }
        }


        protected override IList<Guid> Ids
        {
            get
            {
                if (string.IsNullOrWhiteSpace(this.fieldIds.Value))
                    return new List<Guid>();
                return this.fieldIds.Value.Split(new char[] { ',' }).Select(id => id.ToGuid()).ToList();

            }
        }
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);




        }
        void ClearInitialDropdown()
        {


        }
        protected void Page_Load(object sender, EventArgs e)
        {
            txtReceiptInfoDelayedDays.Attributes.Add("readonly", "readonly");
            //txtPlannedShippingDateCalendarExtender1.Format = SystemConfiguration.DateFormat;
            txtReceiptInfoActualResponseDate_CalendarExtender1.Format = SystemConfiguration.DateFormat;

            this.txtReceiptInfoActualResponseDate.Attributes.Add("onchange", "calculateDelayedDays(this);");
            // this.txtReceiptInfoPlannedResponseDate.Attributes.Add("onchange", "calculateDelayedDays(this);");

            this.txtReceiptInfoOnWayDays.Attributes.Add("onchange", "calculateReceiptInfoPlannedResponseDate();");
            ddlReceiptInfoOnWayUnit.Attributes.Add("onchange", "calculateReceiptInfoPlannedResponseDate();");

            if (!IsPostBack)
            {
                CancelButton = btnCancel;

            }
        }

        private void LoadInitialView()
        {

            CurrentIndex = -1;
            LoadUserControl(Ids.Count > 0 ? Ids[++CurrentIndex] : Guid.Empty);
            SetButtonState(Ids.Count <= 0, true, false, Ids.Count == 1);

        }

        public void LoadUserControl(Guid id)
        {
            Id = id;


            var orderService = ServiceContainer.GetService<IIssuingOrderReceiptInfoTrackService>();
            var receiptTrackData = orderService.GetIssuingOrderReceiptInfoTrack(Id);
            //fieldOrderQuantity.Value = issuingOrderData.OrderQuantity.ToString();
            ClearInitialDropdown();
            FormPanelIssuringOrderInfo.DataSource = receiptTrackData;
            FormPanelIssuringOrderInfo.DataBind();

            ddlIsReceiptInfoExceptional.SelectedValue = receiptTrackData.IsReceiptInfoExceptional
                                                            ? YesOrNo.Yes.ToString()
                                                            : YesOrNo.No.ToString();





            var issuingOrderService = ServiceContainer.GetService<IIssuingOrderService>();
            var issuingOrderData = issuingOrderService.GetIssuingOrder(receiptTrackData.IssuingOrderId);

            FormPanelBasicInfo.DataSource = issuingOrderData;
            FormPanelBasicInfo.DataBind();


            var issuingOrderDelivery = issuingOrderService.GetIssuingOrderDelivery(receiptTrackData.IssuingOrderDeliveryId);
            (this.FormPanelBasicInfo.FindControl("lblDeliveryCity") as Label).Text =
                issuingOrderDelivery.DeliveryCityName;

            //FormPanelIssuingOrderDelivery.DataSource = issuingOrderDelivery;
            //FormPanelIssuingOrderDelivery.DataBind();

            if (string.IsNullOrWhiteSpace(this.txtReceiptInfoOnWayDays.Text))
            {
                var service = ServiceContainer.GetService<IGoodsTravelDaysConfigService>();
                var goodsTravelConfigData =
                    service.GetGoodsTravelDaysConfigDatasByCondition(new GoodsTravelDaysConfigSearchCriteria()
                    {
                        AreaId = CurrentApplicationContext.CompanyId,
                        DeliveryCity = issuingOrderDelivery.DeliveryCity,
                        RouteTypeId = issuingOrderData.RouteTypeId
                    });
                if (goodsTravelConfigData != null)
                {
                    if (goodsTravelConfigData.ReceiptOnWayDays.HasValue)
                    {
                        txtReceiptInfoOnWayDays.Text = goodsTravelConfigData.ReceiptOnWayDays.Value.ToString();
                        if (goodsTravelConfigData.GoodsTravelDaysUnit.HasValue)
                            ddlReceiptInfoOnWayUnit.SelectedValue =
                                goodsTravelConfigData.GoodsTravelDaysUnit.Value.ToString();
                    }
                }
            }
            else
            {
                if (receiptTrackData.ReceiptOnWayDaysUnit.HasValue)
                    ddlReceiptInfoOnWayUnit.SelectedValue = receiptTrackData.ReceiptOnWayDaysUnit.Value.ToString();
            }

            var issuingOrderDeliveryData = issuingOrderService.GetIssuingOrderDelivery(receiptTrackData.IssuingOrderDeliveryId);
            var labelDeliveryOrderCode = FormPanelBasicInfo.FindControl("lblDeliveryOrderCode");
            if (labelDeliveryOrderCode != null)
            {

                (labelDeliveryOrderCode as Label).Text = issuingOrderDeliveryData.DeliveryOrderCode;
            }
            var lblDeliveryAdress = FormPanelBasicInfo.FindControl("lblDeliveryAdress");
            if (lblDeliveryAdress != null)
            {
                (lblDeliveryAdress as Label).Text = issuingOrderDeliveryData.DeliveryAddress;
            }
            var issuingOrderVehicleInfo = issuingOrderService.GetIssuingOrderVehicleInfo(receiptTrackData.IssuingOrderId);
            GridViewDriverInfo.DataSource = issuingOrderVehicleInfo;
            GridViewDriverInfo.DataBind();

            var onwayTrackData =
                ServiceContainer.GetService<IIssuingOrderOnWayTrackService>().GetIssuingOrderOnWayTrackByIssuingOrderId(receiptTrackData.IssuingOrderId);

            var plannedGoodsDeliveryDate = onwayTrackData.PlannedGoodsDeliveredDate ?? DateTime.Now;
            hiddenplannedGoodsDeliveryDate.Value = plannedGoodsDeliveryDate.ToString("yyyy-MM-dd HH:mm:ss"); ;

            if (string.IsNullOrWhiteSpace(txtReceiptInfoPlannedResponseDate.Text))
            {
                if (ddlReceiptInfoOnWayUnit.SelectedValue == "0")
                {
                    txtReceiptInfoPlannedResponseDate.Text = plannedGoodsDeliveryDate.AddDays(txtReceiptInfoOnWayDays.Text.ToInt32() ?? 0).ToString("yyyy-MM-dd");
                }
                else
                {
                    txtReceiptInfoPlannedResponseDate.Text = plannedGoodsDeliveryDate.AddHours(txtReceiptInfoOnWayDays.Text.ToInt32() ?? 0).ToString("yyyy-MM-dd");
                }


            }

            if (string.IsNullOrWhiteSpace(txtReceiptInfoActualResponseDate.Text))
            {

                if (ddlReceiptInfoOnWayUnit.SelectedValue == "0")
                {
                    txtReceiptInfoActualResponseDate.Text = ((onwayTrackData.PlannedGoodsDeliveredDate ?? DateTime.Now).AddDays(txtReceiptInfoOnWayDays.Text.ToInt32() ?? 0)).ToString("yyyy-MM-dd");
                }
                else
                {
                    txtReceiptInfoActualResponseDate.Text = ((onwayTrackData.PlannedGoodsDeliveredDate ?? DateTime.Now).AddHours(txtReceiptInfoOnWayDays.Text.ToInt32() ?? 0)).ToString("yyyy-MM-dd");
                }

            }

            if (receiptTrackData.ReceiptInfoDelayedDays > 0)
            {
                this.txtReceiptInfoDelayedDays.Style.Add("color", "#FF6600");
            }



            IssuingOrderReceiptInfoTrackComments = orderService.GetIssuingOrderReceiptInfoTrackCommentById(Id).ToList();
            AddEmptyIssuingOrderDeliveryAndBind();
            OrderStatus = issuingOrderData.OrderStatus;
            FormPanelIssuringOrderInfo.Enabled = IsEditable();

        }

        protected override bool IsEditable()
        {
            if (IsManager()) return true;
            return OrderStatus == OrderStatus.OnWayTrackCompleted; ;
        }

        void SetButtonState(bool isAdd, bool isFirst, bool isLast, bool isSingleEdit)
        {

            SetButtonState(isAdd, isFirst, isLast, isSingleEdit, this.btnSave, btnCancel, btnPrevious, btnNext, btnSaveAndPrevious, btnSaveAndNext, panelBasic);

        }

        public bool SaveOrder()
        {

            DateTime receiptInfoActualResponseDate = DateTime.MinValue;
            if (!string.IsNullOrWhiteSpace(txtReceiptInfoActualResponseDate.Text))
            {
                if (!DateTime.TryParse(txtReceiptInfoActualResponseDate.Text, out receiptInfoActualResponseDate))
                {
                    //Alert("请输入合法的回单实回日期。");
                    return false;
                }
            }

            var service = ServiceContainer.GetService<IIssuingOrderReceiptInfoTrackService>();
            var receiptInfoTrackData = service.GetIssuingOrderReceiptInfoTrack(Id);
            receiptInfoTrackData.ReceiptInfoCopies = this.txtReceiptInfoCopies.Text.ToInt32() ?? 0;

            receiptInfoTrackData.ReceiptOnWayDays = this.txtReceiptInfoOnWayDays.Text.ToInt32();
            receiptInfoTrackData.ReceiptOnWayDaysUnit = int.Parse(this.ddlReceiptInfoOnWayUnit.SelectedValue);




            DateTime plannedGoodsDeliveredDate;
            if (DateTime.TryParse(hiddenplannedGoodsDeliveryDate.Value, out plannedGoodsDeliveredDate))
            {

                if (receiptInfoTrackData.ReceiptOnWayDays.HasValue)
                {
                    plannedGoodsDeliveredDate = receiptInfoTrackData.ReceiptOnWayDaysUnit == 0 ? plannedGoodsDeliveredDate.AddDays(receiptInfoTrackData.ReceiptOnWayDays.Value) : plannedGoodsDeliveredDate.AddHours(receiptInfoTrackData.ReceiptOnWayDays.Value);
                  

                }
                receiptInfoTrackData.ReceiptInfoPlannedResponseDate = plannedGoodsDeliveredDate;
            }
            else
            {
                receiptInfoTrackData.ReceiptInfoPlannedResponseDate = null;
            }



            if (receiptInfoActualResponseDate != DateTime.MinValue)
            {
                receiptInfoTrackData.ReceiptInfoActualResponseDate = receiptInfoActualResponseDate;
            }
            else
            {
                receiptInfoTrackData.ReceiptInfoPlannedResponseDate = null;
            }

            if (receiptInfoTrackData.ReceiptInfoPlannedResponseDate != DateTime.MinValue && receiptInfoActualResponseDate != DateTime.MinValue)
            {
                receiptInfoTrackData.ReceiptInfoDelayedDays = SystemUtility.GetDelayedDays(receiptInfoTrackData.ReceiptInfoPlannedResponseDate,
                                                                                       receiptInfoActualResponseDate);

            }

            receiptInfoTrackData.ReceiptInfoNotReceived =
                StringUtilities.Trim(this.txtReceiptInfoNotReceived.Text.Trim());
            receiptInfoTrackData.IsReceiptInfoDelayed = receiptInfoTrackData.ReceiptInfoDelayedDays > 0;
            receiptInfoTrackData.IsReceiptInfoExceptional = ddlIsReceiptInfoExceptional.SelectedValue ==
                                                            YesOrNo.Yes.ToString();


            receiptInfoTrackData.LastUpdatedBy = CurrentApplicationContext.UserId;
            receiptInfoTrackData.LastUpdatedDate = DateTime.Now;

            ExtractIssuingOrderDelivery();
            receiptInfoTrackData.IssuingOrderReceiptInfoTrackCommentList = IssuingOrderReceiptInfoTrackComments;

            var result = service.ModifyIssuingOrderReceiptInfoTrack(receiptInfoTrackData);
            if (result)
            {

                Success("保存成功!");
            }


            return result;
        }


        private bool IsLastRow(int rowIndex)
        {
            return IssuingOrderReceiptInfoTrackComments.Count() == rowIndex + 1;
        }

        protected void gridIssuingOrderDelivery_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var issuingOrderDeliveryId = (e.Row.DataItem as IssuingOrderReceiptInfoTrackCommentData).Id.ToString();

                var btnDelete = (ImageButton)e.Row.FindControl("btnDelete");
                if (btnDelete != null)
                {
                    btnDelete.OnClientClick = string.Format("deleteIssuingOrderDeliveryId('{0}');return false;",
                                                            issuingOrderDeliveryId);
                }

                var txtReceiptInfoExceptions = (TextBox)e.Row.FindControl("txtReceiptInfoExceptions");
                var txtRemark = (TextBox)e.Row.FindControl("txtRemark");

                txtReceiptInfoExceptions.Attributes.Remove("onblur");
                if (IsLastRow(e.Row.RowIndex))
                {

                    txtReceiptInfoExceptions.Attributes.Add("onblur",
                                                        "onChangeGoodsDelayedReasons(this,'" + txtRemark.ClientID +
                                                        "');return false;");
                }

            }
        }


        public void btnReceiptInfoExceptions_Click(object sender, EventArgs e)
        {

            if (!string.IsNullOrWhiteSpace(hiddenReceiptInfoExceptions.Value))
            {
                ExtractIssuingOrderDelivery();
            }

            AddEmptyIssuingOrderDeliveryAndBind();

        }

        private void AddEmptyIssuingOrderDeliveryAndBind()
        {
            var tempIssuingOrderOnWayTrackComments = IssuingOrderReceiptInfoTrackComments;
            tempIssuingOrderOnWayTrackComments.Add(new IssuingOrderReceiptInfoTrackCommentData()
            {
                Id = Guid.NewGuid(),
                ReceiptInfoExceptions = string.Empty

            });
            IssuingOrderReceiptInfoTrackComments = tempIssuingOrderOnWayTrackComments; //update viewstate
            gridOrderDetailList.DataSource = IssuingOrderReceiptInfoTrackComments;
            gridOrderDetailList.DataBind();
        }

        private void ExtractIssuingOrderDelivery()
        {
            var tempIssuingOrderOnWayTrackComments = new List<IssuingOrderReceiptInfoTrackCommentData>();
            foreach (GridViewRow detailRow in gridOrderDetailList.Rows)
            {
                var issuingOrderOnWayTrackCommentId = gridOrderDetailList.DataKeys[detailRow.RowIndex]["Id"].ToString().ToGuid();
                var issuingOrderOnWayTrackComment = IssuingOrderReceiptInfoTrackComments.FirstOrDefault(src => src.Id == issuingOrderOnWayTrackCommentId);

                if (issuingOrderOnWayTrackComment != null)
                {
                    issuingOrderOnWayTrackComment.IssuingOrderReceiptInfoTrackId = Id;

                    issuingOrderOnWayTrackComment.ReceiptInfoExceptions = (detailRow.FindControl("txtReceiptInfoExceptions") as TextBox).Text;

                    tempIssuingOrderOnWayTrackComments.Add(issuingOrderOnWayTrackComment);
                }

            }

            //update viewstate
            IssuingOrderReceiptInfoTrackComments = tempIssuingOrderOnWayTrackComments;
        }

        protected void btnhiddenIssuingOrderReceiptTrackCommentDelete_Click(object sender, EventArgs e)
        {
            var issuingOrderDeliveryId = hiddenIssuingOrderReceiptTrackCommentId.Value.ToGuid();
            var issuingOrderDelivery =
                IssuingOrderReceiptInfoTrackComments.FirstOrDefault(src => src.Id == issuingOrderDeliveryId);
            if (issuingOrderDelivery != null)
            {
                IssuingOrderReceiptInfoTrackComments.Remove(issuingOrderDelivery);
                //delete from database
                var service = ServiceContainer.GetService<IIssuingOrderReceiptInfoTrackService>();
                service.RemoveIssuingOrderReceiptInfoTrackComment(issuingOrderDeliveryId);
            }

            gridOrderDetailList.DataSource = IssuingOrderReceiptInfoTrackComments;
            gridOrderDetailList.DataBind();
        }

        protected void btnReLoadIds_Click(object sender, EventArgs e)
        {
            LoadInitialView();
            btnReLoadIds.Enabled = false;
        }


        protected void btnSaveAndNext_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {

                btnNext_Click(sender, e);

            }
        }
        protected void btnSaveAndPrevious_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {

                btnPrevious_Click(sender, e);

            }
        }
        protected void btnNext_Click(object sender, EventArgs e)
        {

            if (HasNextView())
            {
                LoadNavigationView(Ids[++CurrentIndex]);
            }

            SetButtonState(false, IsFirstView, IsLastView, false);



        }
        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            if (HasPreviousView())
            {
                LoadNavigationView(Ids[--CurrentIndex]);

            }
            SetButtonState(false, IsFirstView, IsLastView, false);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (SaveOrder())
            {
                CloseWindow(true);
            }

        }


        internal void LoadNavigationView(Guid id)
        {

            Id = id;

            LoadUserControl(id);

        }


    }
}